package ar.edu.itba.pod.legajo45002;

import java.rmi.AlreadyBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.LinkedList;
import java.util.List;

import ar.edu.itba.balance.api.AgentsTransfer;
import ar.edu.itba.balance.api.NodeAgent;
import ar.edu.itba.node.Node;
import ar.edu.itba.pod.agent.runner.Agent;
import ar.edu.itba.pod.agent.runner.Simulation;

@SuppressWarnings("serial")
public class AgentsTransferImpl extends UnicastRemoteObject implements AgentsTransfer{

	protected AgentsTransferImpl() throws RemoteException {
		super();
		Registry reg = DistributedNodeImpl.getRegistry();
		if( reg != null){
			try {
				System.out.println("registering agents transfer");
				reg.bind(Node.AGENTS_TRANSFER, this);
			} catch (AlreadyBoundException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void runAgentsOnNode(List<NodeAgent> agents) throws RemoteException {
		System.out.println("going to add " + agents.size() + " agents on this node");
		for( NodeAgent nodeAgent : agents){
			DistributedNodeImpl.getSimulation().add(nodeAgent.agent());
		}
		System.out.println("agents running: "+DistributedNodeImpl.getSimulation().agentsRunning()) ;
	}

	@Override
	public int getNumberOfAgents() throws RemoteException {
		System.out.println("returning number of agents: "+ DistributedNodeImpl.getSimulation().agentsRunning());
		return DistributedNodeImpl.getSimulation().agentsRunning();
	}

	@Override
	public List<NodeAgent> stopAndGet(int numberOfAgents) throws RemoteException {
		
		Simulation simulation = DistributedNodeImpl.getSimulation();
		List<Agent> agents = simulation.getAgentsRunning();
		List<NodeAgent>agentsToTransfer = new LinkedList<NodeAgent>();
		System.out.println("Stopping: " + numberOfAgents+" agents");
		for (Agent agent : agents.subList(0, numberOfAgents)){
			simulation.remove(agent);
			agentsToTransfer.add(new NodeAgent(DistributedNodeImpl.getMynodeInfo(), agent));
		}
		
		return agentsToTransfer;
	}

}
